using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class MyCustomModules_Consultations : System.Web.UI.UserControl
{
    string conn = System.Configuration.ConfigurationManager.AppSettings.Get("MSSQLConnectionString");
    DataSet ds = new DataSet();
    Guid uguid;
    
    protected void Page_Load(object sender, EventArgs e)
    {

        GetUserGUID();

        GetAllMessages();

        if (!IsPostBack)
        {
            drpSubject.Style.Add("display", "none");
            drpSubject.Style.Add("position", "absolute");
            FillSubjectDropDown();
            FillMessageWidgets(false);
        }
       
    }

    protected void GetUserGUID()
    {
        System.Data.SqlClient.SqlDataReader dr = mojoPortal.Data.SqlHelper.ExecuteReader
          (conn, CommandType.StoredProcedure, "usp_GetUserDetails",
          new System.Data.SqlClient.SqlParameter("@UserEmail", HttpContext.Current.User.Identity.Name.ToString()));
        if (dr.HasRows)
        {
            dr.Read();
            uguid = new Guid(dr["UserGuid"].ToString());
        }
        dr.Close();
    }

    protected void GetAllMessages()
    {
        Guid guidTemp;
        if (Request.QueryString["UserGUID"] != null)
            guidTemp = new Guid(Request.QueryString["UserGUID"].ToString());
        else
            guidTemp = new Guid(uguid.ToString());


        // Get status information
        ds = mojoPortal.Data.SqlHelper.ExecuteDataset(
            conn, CommandType.StoredProcedure, "usp_GetConsultationMessages",
            new System.Data.SqlClient.SqlParameter("@PostedBy", guidTemp));
        
        DataSet dsTemp = new DataSet();
        DataTable dt = ds.Tables[1].Copy();
        dsTemp.Tables.Add(dt);

        Session["MessagesPosted"] = dsTemp ;
    }

    protected void btnPostMessage_Click(object sender, EventArgs e)
    {
       
        // Add new messages here
        mojoPortal.Data.SqlParameterHelper sph = new mojoPortal.Data.SqlParameterHelper(conn, "usp_InsertNewConsultationMessage", CommandType.StoredProcedure, 3);
        sph.DefineSqlParameter("@Subject", SqlDbType.NVarChar, ParameterDirection.Input, txtNewSubject.Text );
        sph.DefineSqlParameter("@Message", SqlDbType.NVarChar, ParameterDirection.Input, txtMessage.Text);
        sph.DefineSqlParameter("@PostedBy", SqlDbType.UniqueIdentifier, ParameterDirection.Input, new Guid( uguid.ToString() ));
        
        if (txtMessage.Text != "" && txtNewSubject.Text != "")
        {
            int result = Convert.ToInt32(sph.ExecuteNonQuery());
            if (result == -1)
            {
                ;// lblMessage.Text = "Error occured";
            }
            else if (result > 0)
            {
                ;// lblMessage.Text = "";
                //Send mail
                SendConfirmationMail();
                txtMessage.Text = "";
                GetAllMessages();
                FillMessageWidgets(true );
            }
            else
                ;// lblMessage.Text = "Error occured";
        }
    }

    protected void FillSubjectDropDown()
    {
        drpSubject.Items.Add( new ListItem(""));
        foreach ( DataRow dr in ds.Tables[0].Rows)
        {
            drpSubject.Items.Add(new ListItem(dr["Text"].ToString()));
        }
    }

    protected void FillMessageWidgets(bool addedNewMessage)
    {
        MyCustomModules_MessageWidget widget;
        Panel pnlSubject;

        // ADD FOR LOOP FOR SUBJECTS
        DataView dvSubs = ds.Tables[0].DefaultView;
        dvSubs.Sort = "SubjectID asc";
        foreach (DataRow drSubs in dvSubs.ToTable().Rows)
        // FOR
        {
            pnlSubject = new Panel();
            pnlSubject.ID = "pnlSubject";
            pnlSubject.GroupingText = drSubs["Text"].ToString();
            if (!addedNewMessage)
                pnlSubject.Height = 30;
            else
            {
                if ( drSubs["Text"].ToString() != txtNewSubject.Text )
                    pnlSubject.Height = 30;
            }
            pnlSubject.ScrollBars = ScrollBars.Vertical;
            pnlSubject.Attributes.Add("ondblclick", "ExpandCollapse(this);");
            pnlSubject.ToolTip = drSubs["Text"].ToString();
            
            DataView dv = ds.Tables[1].DefaultView;
            dv.RowFilter = "SubID=" + drSubs["SubjectID"].ToString();
            dv.Sort = "MessageID asc";
            foreach (DataRow dr in dv.ToTable().Rows)
            {
                widget = (MyCustomModules_MessageWidget)LoadControl("~/MyCustomModules/MessageWidget.ascx");
                widget.strMessageID = dr["MessageID"].ToString();
                if (Request.QueryString["userid"] != null)
                    widget.strCurrentUser = Request.QueryString["userid"].ToString();
                pnlSubject.Controls.Add(widget);
            }

            pnlPostMessage.Controls.Add(pnlSubject);
        } // END FOR SUBJECTS
    }

    protected void SendConfirmationMail()
    {
        // FullName - get from getuserdetails
        // Updated By - httpcontext
        // Stauts Message - from grid
        // Send to - get from getuserdetails
        
        // DocumentName - from docid
        
        // StatusComments - from grid
        // StatusDateTime - datetime.now

        
        // 
        string strTo = String.Empty;
        string strCC = String.Empty;
        string strFilePath = String.Empty;

        MailMerge msg = new MailMerge("PostConsultation");
        msg.StatusDateTime = DateTime.Now.ToString("dd-MMM-yyyy HH:mm:ss");

        msg.FullName = "Admin";
        strTo = System.Configuration.ConfigurationManager.AppSettings.Get("SMTPTo");

        if (Request.QueryString["UserGUID"] != null)
        {
            System.Data.SqlClient.SqlDataReader dr = mojoPortal.Data.SqlHelper.ExecuteReader
               (conn, CommandType.StoredProcedure, "usp_GetUserByGUID",
               new System.Data.SqlClient.SqlParameter("@guid", new Guid(Request.QueryString["UserGUID"].ToString())));
            if (dr.HasRows)
            {
                dr.Read();

                if (HttpContext.Current.User.IsInRole("Content Administrators") || HttpContext.Current.User.IsInRole("Admins"))
                {
                    msg.FullName = dr["name"].ToString();
                    strTo = dr["email"].ToString();
                }
            }
            dr.Close();
        }

        System.Data.SqlClient.SqlDataReader drUser = mojoPortal.Data.SqlHelper.ExecuteReader
           (conn, CommandType.StoredProcedure, "usp_GetUserDetails",
           new System.Data.SqlClient.SqlParameter("@UserEmail", HttpContext.Current.User.Identity.Name.ToString()));
        if (drUser.HasRows)
        {
            drUser.Read();
            msg.UpdatedBy = drUser["name"].ToString();
            msg.StatusMessage = txtMessage.Text;

           

        }
        drUser.Close();

        msg.GetMailDetails();

        Common.SendMailMessage(strTo, "", "", msg.Subject, msg.Body);
        //MailHelper.SendMailMessage(strTo, "", "", msg);
    }
}
